package com.ruoyi.iot.exchange.facade;

import com.ruoyi.iot.domain.IotDevice;
import com.ruoyi.iot.redis.NetworkRedis;
import com.ruoyi.iot.redis.enity.NetworkMO;
import com.ruoyi.iot.service.impl.IotDeviceServiceImpl;
import com.ruoyi.iot.service.impl.IotProjectServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * 门面模式，用来注册服务
 */
@Component
public class ServerFacade implements IFacade {

    static ServerFacade serverFacade = null;

    /**
     * 远程服务调用
     */
    @Autowired
    public IotDeviceServiceImpl iotDeviceService;





    /**
     * 项目服务
     */
    @Autowired
    IotProjectServiceImpl iotProjectService;

    /**
     * 网络服务的Redis
     */
    @Autowired
    private NetworkRedis networkRedis;



    public static ServerFacade getInstance(){
        return serverFacade;
    }

    @PostConstruct
    public void initFactory(){
        serverFacade = this;
    }


    @Override
    public IotDevice selectIotDeviceByDevCode(String devCode) {

        return iotDeviceService.selectIotDeviceByDevCode(devCode);
    }

    @Override
    public void reportIotDeviceOnline(String devCode) {
        iotDeviceService.reportIotDeviceOnline(devCode);

        NetworkMO networkMO = new NetworkMO();
        networkMO.setDevId(devCode);
        networkMO.setOnline(true);
        networkMO.setTime(new Date());

        IotDevice iotDevice = iotDeviceService.selectIotDeviceByDevNum(devCode);
        String remark = iotDevice.getRemark();
        networkMO.setRemark(remark);
        String projectName =  iotProjectService.selectIotProjectById(iotDevice.getProjectId()).getName();
        networkMO.setProjectName(projectName);
        networkMO.setProjectId(iotDevice.getProjectId());

        networkRedis.push(networkMO);
        networkRedis.publish(networkMO);

    }

    @Override
    public void reportIotDeviceOffline(String devCode) {
        iotDeviceService.reportIotDeviceOffline(devCode);

        NetworkMO networkMO = new NetworkMO();
        networkMO.setDevId(devCode);
        networkMO.setOnline(false);
        networkMO.setTime(new Date());

        IotDevice iotDevice = iotDeviceService.selectIotDeviceByDevNum(devCode);
        String remark = iotDevice.getRemark();
        networkMO.setRemark(remark);
        String projectName =  iotProjectService.selectIotProjectById(iotDevice.getProjectId()).getName();
        networkMO.setProjectName(projectName);
        networkMO.setProjectId(iotDevice.getProjectId());

        networkRedis.push(networkMO);
        networkRedis.publish(networkMO);
    }



}
